package com.netmi.myjectpack.startup;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.netmi.myjectpack.R;
import com.netmi.myjectpack.bean.MyRealmUserInfo;
import com.netmi.myjectpack.bean.UserInfo;
import com.netmi.myjectpack.databinding.FragmentStartupRealmBinding;

import java.util.List;
import java.util.Random;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * 类描述：
 * 创建人：tgw
 * 创建时间：2020/8/6
 * 修改备注：
 */
public class RealmFragment extends Fragment {
    public static final String TAG = RealmFragment.class.getName();

    private FragmentStartupRealmBinding mBinding;

    private UserInfo info;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mBinding == null)
            mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_startup_realm, container, false);
        return mBinding.getRoot();
    }


    //使用databin绑定点击事件
    public void doClick(View view) {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        MyRealmUserInfo people = realm.createObject(MyRealmUserInfo.class); // Create a new object
        people.setNickname("realm插入数据" + new Random().nextInt(100));
        realm.commitTransaction();

        //显示数据库最后一条
        mBinding.tvName.setText(queryAllPeople(realm).get(queryAllPeople(realm).size() - 1).getNickname());

    }

    public List<MyRealmUserInfo> queryAllPeople(Realm realm) {
        realm = Realm.getDefaultInstance();
        RealmResults<MyRealmUserInfo> peoples = realm.where(MyRealmUserInfo.class).findAll();
        return realm.copyFromRealm(peoples);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        info = new UserInfo();
        info.setNickname("tgw");
        //清除在AndroidManifest中使用的禁用
//        如果AndroidManifest文件中
//         <meta-data
//        android:name="com.netmi.myjectpack.startup.RealmManagerInitializer"
//        android:value="androidx.startup"
//        tools:node="remove" />  //使用了该句话 就是禁用改库的初始化
        //一旦禁用可使用该方法解禁
//        AppInitializer.getInstance(getContext())
//                .initializeComponent(RealmManagerInitializer.class);
        //databinding的绑定事件
        mBinding.setLiveDataFragment(RealmFragment.this);
    }
}
